package com.harry.greendaomaster.view;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.harry.greendaomaster.MyApp;
import com.harry.greendaomaster.R;
import com.harry.greendaomaster.adapter.UserAdapter;
import com.harry.greendaomaster.base.BaseActivity;
import com.harry.greendaomaster.db.User;
import com.harry.greendaomaster.greendao.gen.DaoSession;
import com.harry.greendaomaster.greendao.gen.JsonDataDao;
import com.harry.greendaomaster.greendao.gen.UserDao;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 拉莫帅
 * @date 2022/1/5
 * @address
 * @Desc MainActivity
 */
public class MainActivity extends BaseActivity implements View.OnClickListener {

    private UserDao userDao;
    private EditText mNumber, mName, mPwd;
    private EditText mMsg;
    private Button mAdd;
    private Button mDelete;
    private Button mUpdate;
    private Button mSelect;
    private Button cleanMath;
    private RecyclerView mRecycle;
    private JsonDataDao jsonDataDao;//模拟数据

    /**
     * 关于有网/无网  >>>> 模拟缓存数据处理(亲测有效)
     * 简单案例：
     * private Gson gson = new Gson();
     * <p>
     * //判断是否联网
     * boolean conn = NetUtilsWork.isConn(MainActivity.this);
     * <p>
     * //无网络
     * if(conn == false){
     * List<GoodsBean> list = jsonDataDao.queryBuilder().build().list();
     * String json = list.get(0).getJson();
     * GoodsBean goodsBean = gson.fromJson(json, GoodsBean.class);
     * List<GoodsBean.DataBean> list = goodsBean.getData();
     * //展示
     * GoodsAdapter myAdapter = new GoodsAdapter(MainActivity.this, list);
     * mRecycle.setAdapter(myAdapter);
     * }else{//有网络
     * <请求后台接口/>
     * }
     * <p>
     * 在网络请求成功的onSuccess()方法中调用
     * public void onSuccess(Object data){
     * if(data != null){
     * String json = gson.toJson(data);
     * GoodsBean goodsBean = gson.fromJson(json,GoodsBean.class);
     * String code = goodsBean.getCode();
     * if(code.equals("200")){
     * List<GoodsBean.DataBean> list = goodsBean.getData();
     * if(list.size() > 0){
     * //清除数据<防止数据重复添加/>
     * jsonDataDao.deleteAll();
     * <p>
     * //展示
     * GoodsAdapter myAdapter = new GoodsAdapter(MainActivity.this, list);
     * mRecycle.setAdapter(myAdapter);.
     * <p>
     * //将数据存储到数据库
     * for(int i = 0;i < list.size(); i++){
     * jsonDataDao.insert(new JsonData(null,list.get(i).getFoods(),list.get(i).getMoney()));
     * }
     * }
     * }else{
     * Toast.makeText(this, goodsBean.getMsg(), Toast.LENGTH_SHORT).show();
     * }
     * }
     * }
     */

    @Override
    protected void initView() {
        mNumber = findViewById(R.id.number);
        mName = findViewById(R.id.name);
        mPwd = findViewById(R.id.pwd);
        mMsg = findViewById(R.id.msg);
        mAdd = findViewById(R.id.add);
        mDelete = findViewById(R.id.delete);
        mUpdate = findViewById(R.id.update);
        mSelect = findViewById(R.id.select);
        cleanMath = findViewById(R.id.cleanMath);
        mRecycle = findViewById(R.id.recycle);
        mAdd.setOnClickListener(this);
        mDelete.setOnClickListener(this);
        mUpdate.setOnClickListener(this);
        mSelect.setOnClickListener(this);
        cleanMath.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        /**
         * 初始化数据库
         */
        DaoSession daoSession = MyApp.getInstances().getDaoSession();
        userDao = daoSession.getUserDao();

        /**
         * 模拟数据
         */
        jsonDataDao = daoSession.getJsonDataDao();
    }

    @Override
    protected int createViews() {
        return R.layout.activity_main;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add:
                insertUser();
                break;
            case R.id.delete:
                deleteUser();
                break;
            case R.id.update:
                updateUser();
                break;
            case R.id.select:
                selectUser();
                break;
            case R.id.cleanMath:
                startActivity(new Intent(this, DataActivity.class));
                break;
        }
    }

    /**
     * 添加
     */
    private void insertUser() {
        String number = mNumber.getText().toString().trim();
        int num = Integer.parseInt(number);
        String userName = mName.getText().toString().trim();
        String passWord = mPwd.getText().toString().trim();

        userDao.insertOrReplace(new User(null, num, userName, passWord));
    }

    /**
     * 删除
     */
    private void deleteUser() {
        String name = mName.getText().toString();
        String passWord = mPwd.getText().toString().trim();

        /**
         * <条件删除>
         *     根据ID删除单条数据
         * </条件删除>
         */
//        long l = userDao.count() - 1;
//        userDao.deleteByKey(l);

        /**
         * <条件删除>
         *      用户名 Username
         *      单个条件删除 eq
         * </条件删除>
         */
        userDao.queryBuilder()
                .where(
                        UserDao.Properties.Username.eq(name)
                ).buildDelete()
                .executeDeleteWithoutDetachingEntities();

        /**
         * <条件删除>
         *      用户名 Username
         *      密码 Password
         *      多条件删除 eq
         * </条件删除>
         */
//        userDao.queryBuilder()
//                .where(
//                        UserDao.Properties.Username.eq(name),
//                        UserDao.Properties.Password.eq(passWord)
//                ).buildDelete()
//                .executeDeleteWithoutDetachingEntities();

        /**
         * 删除全部数据
         */
//        userDao.deleteAll();
    }

    /**
     * 修改
     */
    private void updateUser() {
        //用户名
        String name = mName.getText().toString();

        //修改后的用户名
        String updateMsg = mMsg.getText().toString();

        /**
         * <条件修改>
         *      用户名 Username
         *      修改多条用户重复数据 eq
         * </条件修改>
         */
        List<User> list = userDao.queryBuilder()
                .where(
                        UserDao.Properties.Username.eq(name)
                ).build()
                .list();

        Log.e("数据", "updateUser: " + list.size());
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setUsername(updateMsg);
                userDao.update(list.get(i));
            }
        }

        /**
         * <条件修改>
         *      用户名 Username
         *      修改单条用户数据 eq
         * </条件修改>
         */
//        User user = userDao.queryBuilder()
//                .where(
//                        UserDao.Properties.Username.eq(name)
//                ).build()
//                .unique();
//
//        Toast.makeText(MainActivity.this, "" + name, Toast.LENGTH_SHORT).show();
//        if (user != null) {
//            user.setUsername(updateMsg);
//
//            userDao.update(user);
//        }
    }

    /**
     * 查询
     */
    private void selectUser() {
        //用户名
        String name = mName.getText().toString();
        String pwd = mPwd.getText().toString();

        /**
         * 查询全部用户数据
         */
        List<User> list = userDao.loadAll();

        /**
         * <条件查询>
         *      用户名 Username
         *      模糊查询 like
         * </条件查询>
         */
//        List<User> list = userDao.queryBuilder()
//                .where(
//                        UserDao.Properties.Username.like("%" + name + "%")
//                ).build()
//                .list();

        /**
         * <条件查询>
         *      用户名 Username
         *      密码 Password
         *      多条件查询 eq
         * </条件查询>
         */
//        List<User> list = userDao.queryBuilder()
//                .where(
//                        UserDao.Properties.Username.eq(name),
//                        UserDao.Properties.Password.eq(pwd)
//                ).build()
//                .list();

        /**
         * <条件查询>
         *      用户名 Username
         *      单条件查询 eq
         * </条件查询>
         */
//        List<User> list = userDao.queryBuilder()
//                .where(
//                        UserDao.Properties.Username.eq(name)
//                ).build()
//                .list();

        /**
         * <条件查询>
         *     自增ID
         *     orderAsc 以字段升序排序
         *     orderDesc 以字段降序
         * </条件查询>
         */
//        List<User> list = userDao.queryBuilder()
//                .orderDesc(UserDao.Properties.Number)
//                .where(
//                        UserDao.Properties.Username.eq(name)
//                )
//                .build()
//                .list();

        Log.e("当前数据集合 >>", "selectUser: " + list.size());
        LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecycle.setLayoutManager(manager);
        UserAdapter userAdapter = new UserAdapter(this, list);
        mRecycle.setAdapter(userAdapter);
    }
}
